<?php

/**
 * My own layer between application and MySQL database.
 * It is designed as an singleton (Design Pattern)
 * @author Honza
 */
class DB {

  private static $c = NULL; // db connection
  private static $showSql = false; // used when debugging

  /**
   * Connect to database
   */
  private static function conect() {
    if ($_SERVER['SERVER_NAME'] == "localhost") {
      $db_name = "elibrary";
      $db_host = "localhost";
      $db_user = "root";
      $db_pass = "";
    } else {
      $db_name = "elibrary";
      $db_host = "localhost";
      $db_user = "mysql_honza";
      $db_pass = "1980diab";
    }
    self::$c = @mysql_connect("$db_host", "$db_user", "$db_pass");
    mysql_select_db($db_name);
    mysql_query("set names 'utf8';");
  }

  /**
   * Executes SQL query
   * @param type $sql_text SQL query to execute
   * @param string $name name of the pk column (optional)
   * @return array asoc array or null
   */
  public static function sql($sql_text, $PKCol = null) {
    $id = -1;
    if (self::$c == NULL) {
      self::conect();
    }

    if (self::$showSql) {
      echo $sql_text . BR;
    }
    
    $res = mysql_query($sql_text);
    if (!$res) {
      echo mysql_error();
    }

    if ($PKCol) {
      //it's insert query
      $id = mysql_insert_id();
    }

    if (strpos($sql_text, "select ") === false) {
      return $id;
    } else {
      $result = array();
      while ($row = mysql_fetch_array($res)) {
        $result[] = $row;
      }
      if (empty($result)) {
        $result = NULL;
      }
      return $result;
    }
  }

  /**
   * Adds row to table.
   * @param type $table - tabulka
   * @param type $atts - array of values
   */
  public static function add($table, $atts = array()) {

    $sql = "insert into " . $table . " values ( ";
    $count = count($atts);
    for ($i = 0; $i < $count; $i++) {
      if ($atts[$i] === '') {
        $atts[$i] = NULL;
      }
      if ($i == $count - 1) {
        $sql .= "'" . $atts[$i] . "'";
      } else {
        $sql .= "'" . $atts[$i] . "', ";
      }
    }
    $sql .= " )";

    $result = self::sql($sql);
    if ($result == NULL) {
      //error
      return 0;
    } else {
      return 1;
    }
  }

  /**
   * TRUE if you want to see all generated SQL queries
   * @param type $bool TRUE or FALSE value
   */
  public static function showSql($bool) {
    self::$showSql = $bool;
  }

  /**
   * Close DB connection
   */
  public static function close() {
    if (self::$c != NULL) {
      mysql_close(self::$c);
      self::$c = NULL;
    }
  }

}

?>
